package com.cn.ant.modules.app.web;

import com.cn.ant.common.config.Global;
import com.cn.ant.common.utils.*;
import com.cn.ant.common.web.BaseController;
import com.cn.ant.modules.school.entity.MajorInfo;
import com.cn.ant.modules.school.entity.School;
import com.cn.ant.modules.school.service.MajorInfoService;
import com.cn.ant.modules.school.service.SchoolService;
import com.cn.ant.modules.score.entity.LqSchool;
import com.cn.ant.modules.score.service.BatchLineService;
import com.cn.ant.modules.score.service.LqMajorService;
import com.cn.ant.modules.score.service.LqSchoolService;
import com.cn.ant.modules.score.service.SchoolLqRateService;
import com.cn.ant.modules.sys.entity.Area;
import com.cn.ant.modules.sys.service.AreaService;
import com.cn.ant.modules.sys.utils.SchoolUtils;
import com.cn.ant.modules.user.entity.UserFavorite;
import com.cn.ant.modules.user.entity.UserMain;
import com.cn.ant.modules.user.service.UserFavoriteService;
import com.cn.ant.modules.user.service.UserMainService;
import com.cn.ant.modules.volunteer.entity.Volunteer;
import com.cn.ant.modules.volunteer.entity.VolunteerSchool;
import com.cn.ant.modules.volunteer.service.VolunteerSchoolService;
import com.cn.ant.modules.volunteer.service.VolunteerService;
import com.cn.ant.modules.wechat.entity.WeiXinNewListItem;
import com.cn.ant.modules.wechat.entity.WeiXinNewListType;
import com.cn.ant.modules.wechat.entity.WeiXinTikit;
import com.cn.ant.modules.wechat.entity.WeixinAccount;
import com.cn.ant.modules.wechat.service.WeiXinNewListItemService;
import com.cn.ant.modules.wechat.service.WeiXinNewListTypeService;
import com.cn.ant.modules.wechat.service.WeiXinTikitService;
import com.cn.ant.modules.wechat.service.WeixinAccountServiceImpl;
import com.cn.ant.modules.wechat.utils.AccessToken;
import com.cn.ant.modules.wechat.utils.TikitSign;
import com.cn.ant.modules.wechat.utils.WeixinUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.*;

/**
 * ClassName:IndexAction Function:微信首页 Date: 2015/9/8 16:21
 *
 * @author huanggenhua
 * @version 1.0
 * @since JDK 1.6
 */
@Controller
@RequestMapping(value = "${wechat}")
public class IndexController extends BaseController {

    @Autowired
    private WeixinAccountServiceImpl weixinAccountService;

    @Autowired
    private WeiXinTikitService tikitService;

    @Autowired
    private UserMainService userMainService;

    @Autowired
    private AreaService areaService;

    @Autowired
    private VolunteerService volunteerService;

    @Autowired
    private SchoolService schoolService;

    @Autowired
    private BatchLineService batchLineService;

    @Autowired
    private MajorInfoService majorInfoService;

    @Autowired
    private VolunteerSchoolService volunteerSchoolService;

    @Autowired
    private UserFavoriteService userFavoriteService;
    @Autowired
    private LqSchoolService lqSchoolService;
    @Autowired
    private LqMajorService lqMajorService;
    @Autowired
    private SchoolLqRateService schoolLqRateService;
    @Autowired
    private WeiXinNewListTypeService newListTypeService;
    @Autowired
    private WeiXinNewListItemService newListItemService;

    @RequestMapping(value = { "", "index" })
    public String index(HttpServletRequest request, HttpServletResponse response) {
        String code = request.getParameter("code");
        String accountId = request.getParameter("state");
        String cuserId = CookieUtils.getCookie(request, "userId");
        String copenId = CookieUtils.getCookie(request, "openId");
        UserMain userData = null;
        if (StringUtils.isBlank(cuserId)) {
            WeixinAccount account = this.weixinAccountService.get(accountId);
            if (account != null) {
                AccessToken accessToken = WeixinUtil.getAccessToken(weixinAccountService, account.getAccountAppId(),
                        account.getAccountAppSecret());
                String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + account.getAccountAppId()
                        + "&secret=" + account.getAccountAppSecret() + "&code=" + code
                        + "&grant_type=authorization_code";
                JSONArray ja = HttpClientUtils.getByJson(url, 10000);
                if ((ja != null) && (ja.size() > 0)) {
                    JSONObject jo = ja.getJSONObject(0);
                    String openId = jo.getString("openid");
                    String access_token = jo.getString("access_token");
                    String expiresIn = jo.getString("expires_in");
                    String refreshToken = jo.getString("refresh_token");
                    UserMain userMain = userMainService.queryUserByOpenId(account.getAccountAppId(), openId);
                    if (userMain != null) {
                        // 根据OPENID获取用户基本信息
                        JSONArray userInfos = HttpClientUtils
                                .getByJson("https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token
                                        + "&openid=" + openId + "&lang=zh_CN", 10000);
                        JSONObject userInfo = userInfos.getJSONObject(0);
                        userMain.setNickName(userInfo.getString("nickname"));
                        userMain.setSex(userInfo.getString("sex"));
                        userMain.setProvince(userInfo.getString("province"));
                        userMain.setCity(userInfo.getString("city"));
                        userMain.setCountry(userInfo.getString("country"));
                        userMain.setHeadPic(userInfo.getString("headimgurl"));
                        userMain.setOpenId(openId);
                        userMain.setAppId(account.getAccountAppId());
                        userMain.setAccessCode(access_token);
                        userMain.setExpiresIn(expiresIn);
                        userMain.setRefreshToken(refreshToken);
                        // 更新用户
                    } else {
                        // 根据OPENID获取用户基本信息
                        JSONArray userInfos = HttpClientUtils
                                .getByJson("https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token
                                        + "&openid=" + openId + "&lang=zh_CN", 10000);
                        JSONObject userInfo = userInfos.getJSONObject(0);
                        userMain = new UserMain();
                        userMain.setNickName(userInfo.getString("nickname"));
                        userMain.setSex(userInfo.getString("sex"));
                        userMain.setProvince(userInfo.getString("province"));
                        userMain.setCity(userInfo.getString("city"));
                        userMain.setCountry(userInfo.getString("country"));
                        userMain.setHeadPic(userInfo.getString("headimgurl"));
                        userMain.setOpenId(openId);
                        userMain.setAppId(account.getAccountAppId());
                        userMain.setAccessCode(access_token);
                        userMain.setExpiresIn(expiresIn);
                        userMain.setRefreshToken(refreshToken);
                        userMain.setAccessTime(DateUtils.getCurrDate());
                        userMain.setRegistTime(DateUtils.getCurrDate());
                        userMain.setAreaCode("43");
                        userMain.setKmType("1");
                        userMain.setGkScore("0");
                        userMain.setBatchLevel("2");
                        // 添加用户
                    }
                    userMainService.save(userMain);
                    userData = userMain;
                    request.setAttribute("user", userMain);
                    CookieUtils.setCookie(response, "userId", userMain.getId());
                    CookieUtils.setCookie(response, "openId", openId);
                }
            }
        } else {
            // 更具userId获取用户信息
            UserMain userMain = userMainService.get(cuserId);
            userData = userMain;
            request.setAttribute("user", userMain);
        }
        // 判断条件是否设置
        if (StringUtils.isNotBlank(userData.getGkScore()) && StringUtils.isNotBlank(userData.getKmType())
                && StringUtils.isNotBlank(userData.getBatchLevel())) {
            request.setAttribute("flag", "success");
        } else {
            request.setAttribute("flag", "error");
        }
        return "app/index";
    }

    @RequestMapping(value = "userCenter")
    public String userCenter(HttpServletRequest request, HttpServletResponse response) {
        String code = request.getParameter("code");
        String accountId = request.getParameter("state");
        WeixinAccount account = this.weixinAccountService.get(accountId);
        String cuserId = CookieUtils.getCookie(request, "userId");
        String copenId = CookieUtils.getCookie(request, "openId");

        if (StringUtils.isNotBlank(cuserId) && StringUtils.isNotBlank(copenId)) {
            // 查询用户的信息
            UserMain userMain = userMainService.get(cuserId);
            request.setAttribute("user", userMain);
        } else {
            if (account != null) {
                AccessToken accessToken = WeixinUtil.getAccessToken(weixinAccountService, account.getAccountAppId(),
                        account.getAccountAppSecret());
                logger.info("用户的code:" + code);
                String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + account.getAccountAppId()
                        + "&secret=" + account.getAccountAppSecret() + "&code=" + code
                        + "&grant_type=authorization_code";
                JSONArray ja = HttpClientUtils.getByJson(url, 10000);
                if ((ja != null) && (ja.size() > 0)) {
                    JSONObject jo = ja.getJSONObject(0);
                    String openId = jo.getString("openid");
                    String access_token = jo.getString("access_token");
                    String expiresIn = jo.getString("expires_in");
                    String refreshToken = jo.getString("refresh_token");
                    // 根据OPenID判断用户是否已经存在
                    UserMain userMain = userMainService.queryUserByOpenId(account.getAccountAppId(), openId);
                    if (userMain != null) {
                        // 根据OPENID获取用户基本信息
                        JSONArray userInfos = HttpClientUtils
                                .getByJson("https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token
                                        + "&openid=" + openId + "&lang=zh_CN", 10000);
                        JSONObject userInfo = userInfos.getJSONObject(0);
                        userMain.setNickName(userInfo.getString("nickname"));
                        userMain.setSex(userInfo.getString("sex"));
                        userMain.setProvince(userInfo.getString("province"));
                        userMain.setCity(userInfo.getString("city"));
                        userMain.setCountry(userInfo.getString("country"));
                        userMain.setHeadPic(userInfo.getString("headimgurl"));
                        userMain.setOpenId(openId);
                        userMain.setAppId(account.getAccountAppId());
                        userMain.setAccessCode(access_token);
                        userMain.setExpiresIn(expiresIn);
                        userMain.setRefreshToken(refreshToken);
                        // 更新用户
                    } else {
                        // 根据OPENID获取用户基本信息
                        JSONArray userInfos = HttpClientUtils
                                .getByJson("https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token
                                        + "&openid=" + openId + "&lang=zh_CN", 10000);
                        JSONObject userInfo = userInfos.getJSONObject(0);
                        userMain = new UserMain();
                        userMain.setNickName(userInfo.getString("nickname"));
                        userMain.setSex(userInfo.getString("sex"));
                        userMain.setProvince(userInfo.getString("province"));
                        userMain.setCity(userInfo.getString("city"));
                        userMain.setCountry(userInfo.getString("country"));
                        userMain.setHeadPic(userInfo.getString("headimgurl"));
                        userMain.setOpenId(openId);
                        userMain.setAppId(account.getAccountAppId());
                        userMain.setAccessCode(access_token);
                        userMain.setExpiresIn(expiresIn);
                        userMain.setRefreshToken(refreshToken);
                        userMain.setAccessTime(DateUtils.getCurrDate());
                        userMain.setRegistTime(DateUtils.getCurrDate());
                        userMain.setAreaCode("43");
                        userMain.setKmType("1");
                        userMain.setGkScore("0");
                        userMain.setBatchLevel("2");
                        // 添加用户
                    }
                    userMainService.save(userMain);
                    request.setAttribute("user", userMain);
                    CookieUtils.setCookie(response, "userId", userMain.getId());
                    CookieUtils.setCookie(response, "openId", openId);
                }
                WeiXinTikit tikit = WeixinUtil.getWeixinTikit(tikitService, accessToken.getToken(),
                        account.getAccountAppId());
                Map tikitMap = TikitSign.sign(tikit.getTikit(),
                        request.getRequestURL() + "?code=" + code + "&state=" + accountId);
            }
        }
        return "app/userCenter";
    }

    @RequestMapping(value = "wechatAuth")
    public String wechatAuth(HttpServletRequest request) {
        String key = request.getParameter("key");
        WeixinAccountServiceImpl weixinAccountService = (WeixinAccountServiceImpl) SpringContextHolder
                .getApplicationContext().getBean("weixinAccountService");
        ResourceBundle bundler = ResourceBundle.getBundle("application");
//        String accountAppId = "wxf403bed3fe5bddcd";
//        String accountid = "2c28ccb925f74253a43ec6c56b2e2d94";
        String accountAppId = "wx293aae640ff34456";
        String accountid = "402881e8461795c201461795c2e90000";
        String redirectUrl = null;
        String forward = request.getParameter("forward");
        try {
            if (StringUtils.isBlank(forward)) {
                redirectUrl = URLEncoder.encode(bundler.getString("domain") + "/wechat/userCenter", "UTF-8");
            } else if (StringUtils.equals(forward, "index")) {
                redirectUrl = URLEncoder.encode(bundler.getString("domain") + "/wechat/index", "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + accountAppId + "" + "&redirect_uri="
                + redirectUrl + "&response_type=code&scope=snsapi_userinfo&state=" + accountid + "#wechat_redirect";
        return "redirect:" + url;
    }

    @RequestMapping(value = "search")
    public String search(HttpServletRequest request) {
        return "app/search";
    }

    /**
     * 更新用户信息
     * 
     * @param request
     * @return
     */
    @RequestMapping(value = "updateUserInfo")
    @ResponseBody
    public AjaxJson updateUserInfo(HttpServletRequest request) {
        AjaxJson result = new AjaxJson();
        String kemu = request.getParameter("kemu");
        String area = request.getParameter("area");
        String batchLine = request.getParameter("batchLine");
        String score = request.getParameter("score");
        String userId = request.getParameter("userId");
        try {
            if (StringUtils.isNotBlank(userId)) {
                // 获取用户信息
                UserMain user = userMainService.get(userId);
                user.setKmType(kemu);
                user.setAreaCode(area);
                user.setBatchLevel(batchLine);
                user.setGkScore(score);
                userMainService.save(user);
                result.setSuccess(true);
                result.setMsg("更新成功");
            } else {
                result.setSuccess(false);
                result.setMsg("用户不能为空");
                return result;
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("系统异常");
            e.printStackTrace();
        }
        return result;
    }

    @RequestMapping(value = "schoolList")
    public String schoolList(HttpServletRequest request) {
        String areaCode = request.getParameter("areaCode"); // 学校地区
        areaCode = StringUtils.isBlank(areaCode)||areaCode.equals("undefined") ? "" : areaCode;
        String majorParentCode = request.getParameter("parentCode"); // 专业大类
        majorParentCode = StringUtils.isBlank(majorParentCode)||majorParentCode.equals("undefined") ? "" : majorParentCode;
        String majorType = request.getParameter("majorType"); // 专业类型
        majorType = StringUtils.isBlank(majorType)||majorType.equals("undefined") ? "" : majorType;
        String schoolType = request.getParameter("typeCode");// 学校类型
        schoolType = StringUtils.isBlank(schoolType)|| schoolType.equals("undefined") ? "" : schoolType;
        String flags = request.getParameter("flags");// 学校标签
        Map<String, Object> params = new HashMap<>();
        params.put("schoolArea", areaCode);
        params.put("majorParentCode", majorParentCode);
        params.put("majorType", majorType);
        params.put("schoolType", schoolType);
        if (StringUtils.isNotBlank(flags)) {
            String[] flagArr = flags.split(",");
            for (int i = 0; i < flagArr.length; i++) {
                if (flagArr[i].equals("211")) {
                    params.put("is211", "1");
                }
                if (flagArr[i].equals("985")) {
                    params.put("is985", "1");
                }
                if (flagArr[i].equals("guofang")) {
                    params.put("guofang", "1");
                }
                if (flagArr[i].equals("yan")) {
                    params.put("yan", "1");
                }
                if (flagArr[i].equals("zhou")) {
                    params.put("zhou", "1");
                }
            }
        }
        List<Map<String, String>> parentMajorList = majorInfoService.queryMajorParentCode("本科");
        String vtype = request.getParameter("vtype");
        String userId = CookieUtils.getCookie(request, "userId");
        UserMain userMain = userMainService.get(userId);
        //查询当前的年份
        int lqYear = lqSchoolService.getCurrYear();
        request.setAttribute("lqYear", lqYear);
        // 生成志愿组合
        int score = Integer.parseInt(userMain.getGkScore());
        List<Volunteer> volunteerList = volunteerService.createVolunteer(score, userMain, vtype, params);
        Volunteer volunteer = null;
        if (volunteerList != null && volunteerList.size() > 0) {
            volunteer = volunteerList.get(0);
        }
        if (volunteer != null) {
            List<VolunteerSchool> volunteerSchoolList1 = volunteer.getVolunteerSchoolList();
            List<VolunteerSchool> volunteerSchoolList = new ArrayList<VolunteerSchool>();
            VolunteerSchool volunteerSchool = null;
            for (int i = 0; i < volunteerSchoolList1.size(); i++) {
                volunteerSchool = volunteerSchoolList1.get(i);
                School school = schoolService.querySchoolForVolunteer(volunteerSchool.getSchoolCode(),volunteerSchool.getSchoolCodeSn(),
                        userMain.getKmType(), userMain.getBatchLevel(),lqYear);
                Map<String, String> params2 = new HashMap<>();
                params2.put("schoolCode", school.getSchoolCode());
                params2.put("schoolCodeSn", school.getSchoolCodeSn());
                params2.put("klType", userMain.getKmType());
                params2.put("batchLevel", userMain.getBatchLevel());
                params2.put("lqYear", String.valueOf(lqYear));
                int tdx = lqSchoolService.getLastTdx(params2);
                if (tdx > 0) {
                    volunteerSchool.setSchool(school);
                    volunteerSchoolList.add(volunteerSchool);
                }
            }
            if (volunteer != null && volunteer.getVolunteerSchoolList() != null) {
                // 保存志愿组合信息
                volunteerService.save(volunteer);
                volunteerSchoolService.batchSave(volunteer.getVolunteerSchoolList());
            }
            request.setAttribute("params",params);
            request.setAttribute("userMain", userMain);
            request.setAttribute("volunteer", volunteer);
            request.setAttribute("volunteerSchoolList", volunteerSchoolList);
            request.setAttribute("parentMajorList", parentMajorList);
        }
        return "app/schoolList";
    }

    @RequestMapping(value = "volunteerDetail")
    public String volunteerDetail(HttpServletRequest request) {
        String userId = CookieUtils.getCookie(request, "userId");
        UserMain userMain = userMainService.get(userId);
        String vid = request.getParameter("vid");
        Volunteer volunteer = volunteerService.getByCode(vid);
        VolunteerSchool param = new VolunteerSchool();
        param.setVId(vid);
        List<VolunteerSchool> volunteerSchoolList = volunteerSchoolService.findList(param);
        VolunteerSchool volunteerSchool = null;
        int currYear = lqSchoolService.getCurrYear();
        for (int i = 0; i < volunteerSchoolList.size(); i++) {
            volunteerSchool = volunteerSchoolList.get(i);
            School school = schoolService.querySchoolForVolunteer(volunteerSchool.getSchoolCode(),volunteerSchool.getSchoolCodeSn(),
                    userMain.getKmType(), userMain.getBatchLevel(),currYear);
            volunteerSchool.setSchool(school);
            volunteerSchoolList.set(i, volunteerSchool);
        }
        request.setAttribute("volunteer", volunteer);
        request.setAttribute("volunteerSchoolList", volunteerSchoolList);
        return "app/schoolList";
    }

    /**
     * 喧嚣详情
     * 
     * @param request
     * @return
     */
    @RequestMapping(value = "schoolDetail")
    public String schoolDetail(HttpServletRequest request) {
        String schoolCode = request.getParameter("schoolCode");
        String schoolCodeSn = request.getParameter("schoolCodeSn");
        String lqRate = request.getParameter("lqRate");
        String userId = CookieUtils.getCookie(request, "userId");
        if (StringUtils.isBlank(userId)) {
            return "redirect:"+ Global.getConfig("wechat")+"/wechatAuth";
        }
        UserMain userMain = userMainService.get(userId);
        School school = schoolService.getByCode(schoolCode, schoolCodeSn);
        int currYear = lqSchoolService.getCurrYear();
        // 查询预测投档分
        int forecastScore = schoolService.getForecastScore(schoolCode, schoolCodeSn, userMain.getKmType(), userMain.getBatchLevel(),currYear);
        // 查询学校专业录取信息
        int year = 0;
        //查询当前的年份
        List<LqSchool> lqSchoolList = lqSchoolService.findBySchoolCode(school.getSchoolCode(), school.getSchoolCodeSn());
        if (lqSchoolList != null && lqSchoolList.size() > 0) {
            for (int i = 0; i < lqSchoolList.size(); i++) {
                LqSchool lqSchool = lqSchoolList.get(i);
                if (year < Integer.parseInt(lqSchool.getLqYear())) {
                    year = Integer.parseInt(lqSchool.getLqYear());
                };
            }
        }
        List<Map<String, String>> schoolMajorList = schoolService.querySchoolMajor(year, schoolCode,schoolCodeSn,
                userMain.getKmType(), userMain.getBatchLevel());
        if (StringUtils.isNotBlank(school.getCityName()) && StringUtils.isNotBlank(school.getProvinceName())) {
            if (school.getProvinceName().trim().equals(school.getCityName().trim())) {
                school.setCityName("");
            }
        }
        //查询学校录取概率
        double rate = schoolLqRateService.queryRate(userMain.getAreaCode(), schoolCode, schoolCodeSn, userMain.getKmType(),userMain.getBatchLevel(), Integer.parseInt(userMain.getGkScore()), currYear);
        request.setAttribute("school", school);
        request.setAttribute("lqRate", lqRate);
        request.setAttribute("userMain", userMain);
        request.setAttribute("userMain", userMain);
        request.setAttribute("forecastScore", forecastScore);
        request.setAttribute("schoolMajorList", schoolMajorList);
        request.setAttribute("year", year);
        request.setAttribute("lqRate", rate);
        return "app/school";
    }

    /**
     * 批次查询
     * 
     * @param request
     * @return
     */
    @RequestMapping(value = "batchList")
    public String batchList(HttpServletRequest request) {
        String province = request.getParameter("province");
        if (StringUtils.isBlank(province)) {
            province = "43";
        }
        Area area = areaService.getByCode(province);
        String provinceName = "不限";
        if (area != null) {
            provinceName = area.getName();
        }
        List<Map<String, String>> wenBatchList = batchLineService.batchList(province, "1");
        List<Map<String, String>> liBatchList = batchLineService.batchList(province, "5");
        request.setAttribute("wenBatchList", wenBatchList);
        request.setAttribute("liBatchList", liBatchList);
        request.setAttribute("province",province);
        request.setAttribute("provinceName",provinceName);
        return "app/batchList";
    }

    /**
     * 专业查询
     * 
     * @param request
     * @return
     */
    @RequestMapping(value = "majorList")
    public String majorList(HttpServletRequest request) {
        List<Map<String, String>> parentMajorList = majorInfoService.queryMajorParentCode("本科");
        List<Map<String, String>> majorTypeList = SchoolUtils.getMajorType("本科");
        List<Map<String, String>> majorList = majorInfoService.queryMajorList("本科");
        request.setAttribute("majorList", majorList);
        request.setAttribute("majorTypeList", majorTypeList);
        request.setAttribute("parentMajorList", parentMajorList);
        return "app/majorList";
    }

    /**
     * 学校排名
     * 
     * @param request
     * @return
     */
    @RequestMapping(value = "rankList")
    public String rankList(HttpServletRequest request) {
        String type = request.getParameter("type");
        type = StringUtils.isBlank(type) ? "5" : type;
        Map<String, Object> params = new HashMap<>();
        params.put("type", type);
        List<Map<String, String>> rankList = schoolService.querySchoolRank(params);

        WeiXinNewListType newListType = newListTypeService.queryByCode("schoolRankList");
        if (newListType != null) {
            List<WeiXinNewListItem> newListItems = newListItemService.queryByTypeId(newListType.getId());
            request.setAttribute("newListItems", newListItems);
        }
        request.setAttribute("rankList", rankList);
        request.setAttribute("type", type);
        return "app/rankList";
    }

    /**
     * 学校查询
     * @param request
     * @return
     */
    @RequestMapping(value = "searchSchool")
    public String searchSchool(HttpServletRequest request) {
        String userId = CookieUtils.getCookie(request, "userId");
        if (StringUtils.isBlank(userId)) {
            return "redirect:"+ Global.getConfig("wechat")+"/wechatAuth";
        }
        UserMain userMain = userMainService.get(userId);
        String areaCode = request.getParameter("areaCode");
        String batchLevel = request.getParameter("batchLevel");
        if (StringUtils.isBlank(batchLevel)) {
            batchLevel = userMain.getBatchLevel();
        }
        String typeCode = request.getParameter("typeCode");
        String flags = request.getParameter("flags");
        if (StringUtils.isBlank(userId)) {
            return "redirect:"+ Global.getConfig("wechat")+"/userCenter";
        }
        Map<String, String> params = new HashMap<>();
        int year = lqSchoolService.getCurrYear();
        params.put("year", String.valueOf(year));
        params.put("kemuType", userMain.getKmType());
        params.put("batchLevel", batchLevel);
        params.put("areaCode", areaCode);
        params.put("typeCode", typeCode);
        if (StringUtils.isNotBlank(flags)) {
            String[] flagArr = flags.split(",");
            for (int i = 0; i < flagArr.length; i++) {
                if (flagArr[i].equals("211")) {
                    params.put("is211", "1");
                }
                if (flagArr[i].equals("985")) {
                    params.put("is985", "1");
                }
                if (flagArr[i].equals("guofang")) {
                    params.put("guofang", "1");
                }
                if (flagArr[i].equals("yan")) {
                    params.put("yan", "1");
                }
                if (flagArr[i].equals("zhou")) {
                    params.put("zhou", "1");
                }
            }
        }
        List<School> schoolList = schoolService.searchSchool(params);
        if (schoolList != null && schoolList.size() > 0) {
            for (int i = 0; i < schoolList.size(); i++) {
                if (schoolList.get(i).getProvinceName().trim().equals(schoolList.get(i).getCityName())) {
                    schoolList.get(i).setCityName("");
                }
            }
        }
        request.setAttribute("userMain", userMain);
        request.setAttribute("schoolList", schoolList);
        request.setAttribute("params", params);
        return "app/schoolSearch";
    }


    @RequestMapping(value = "getMajorType")
    @ResponseBody
    public List<Map<String, String>> getMajorType(HttpServletRequest request) {
        String parentCode = request.getParameter("parentCode");
        List<Map<String, String>> result = new ArrayList<>();
        if (StringUtils.isNotBlank(parentCode)) {
            List<Map<String, String>> majorTypeList = SchoolUtils.getMajorType("本科");
            for (int i = 0; i < majorTypeList.size(); i++) {
                if (majorTypeList.get(i).get("majorParentCode").equals(parentCode)) {
                    result.add(majorTypeList.get(i));
                }
            }
        }
        return result;
    }

    @RequestMapping(value = "favorite")
    @ResponseBody
    public AjaxJson favorite(HttpServletRequest request) {
        AjaxJson result = new AjaxJson();
        String userId = CookieUtils.getCookie(request, "userId");
        if (StringUtils.isNotBlank(userId)) {
            String type = request.getParameter("type");
            String vid = request.getParameter("vid");
            String schoolCode = request.getParameter("schoolCode");
            String schoolCodeSn = request.getParameter("schoolCodeSn");
            String majorCode = request.getParameter("majorCode");
            UserFavorite favorite = new UserFavorite();
            favorite.setType(type);
            favorite.setUserId(userId);
            favorite.setVolunteerId(vid);
            favorite.setSchoolCode(schoolCode);
            favorite.setSchoolCodeSn(schoolCodeSn);
            favorite.setMajorCode(majorCode);
            favorite.setFavoriteTime(DateUtils.getCurrDate());
            // 判断是否已经收藏
            List<UserFavorite> favoriteList = userFavoriteService.findList(favorite);
            if (favoriteList != null && favoriteList.size() > 0) {
                result.setSuccess(true);
                result.setMsg("已收藏");
            } else {
                userFavoriteService.save(favorite);
            }
            result.setSuccess(true);
            result.setMsg("收藏成功");
        } else {
            result.setSuccess(false);
            result.setMsg("请先登录");
        }
        return result;
    }

    @RequestMapping(value = "unFavorite")
    @ResponseBody
    public AjaxJson unFavorite(HttpServletRequest request) {
        AjaxJson result = new AjaxJson();
        String userId = CookieUtils.getCookie(request, "userId");
        if (StringUtils.isNotBlank(userId)) {
            String type = request.getParameter("type");
            String vid = request.getParameter("vid");
            String schoolCode = request.getParameter("schoolCode");
            String schoolCodeSn = request.getParameter("schoolCodeSn");
            String majorCode = request.getParameter("majorCode");
            UserFavorite favorite = new UserFavorite();
            favorite.setUserId(userId);
            favorite.setType(type);
            favorite.setVolunteerId(vid);
            favorite.setSchoolCode(schoolCode);
            favorite.setSchoolCodeSn(schoolCodeSn);
            favorite.setMajorCode(majorCode);
            // 删除收藏信息
            userFavoriteService.deleteByType(favorite);
            result.setSuccess(true);
            result.setMsg("取消成功");
        } else {
            result.setSuccess(false);
            result.setMsg("请先登录");
        }
        return result;
    }

    /**
     * 用户收藏学校
     * 
     * @param request
     * @return
     */
    @RequestMapping(value = "favschool")
    public String favschool(HttpServletRequest request) {
        String userId = CookieUtils.getCookie(request, "userId");
        if (StringUtils.isNotBlank(userId)) {
            Map<String, String> params = new HashMap<>();
            params.put("userId", userId);
            List<Map<String, String>> favSchoolList = schoolService.queryFavSchool(params);
            request.setAttribute("favSchoolList", favSchoolList);
        }
        return "app/favschool";
    }

    @RequestMapping(value = "favVolunteer")
    public String favVolunteer(HttpServletRequest request){
        String userId = CookieUtils.getCookie(request, "userId");
        if (StringUtils.isNotBlank(userId)) {
            List<Map<String, String>> volunteerList = volunteerService.findVolunteer(userId);
            request.setAttribute("volunteerList", volunteerList);
        }
        return "app/favvolunteer";
    }

    @RequestMapping(value = "favMajor")
    public String favMajor(HttpServletRequest request) {
        String userId = CookieUtils.getCookie(request, "userId");
        if (StringUtils.isNotBlank(userId)) {
            List<Map<String, String>> favMajorList = majorInfoService.queryFavMajor(userId);
            request.setAttribute("favMajorList", favMajorList);
        }
        return "app/favmajor";
    }

    @RequestMapping(value = "majorDetail")
    public String majorDetail(HttpServletRequest request) {
        String majorCode = request.getParameter("majorCode");
        String userId = CookieUtils.getCookie(request, "userId");
        UserMain userMain = userMainService.get(userId);
        MajorInfo majorInfo = majorInfoService.getByCode(majorCode);
        int currYear = lqSchoolService.getCurrYear();
        int maxYear = lqMajorService.queryLqMajorMaxYear(majorCode, userMain.getKmType(), userMain.getBatchLevel());
        List<Map<String, String>> lqMajorList = lqMajorService.queryMajorCode(majorCode, userMain.getKmType(), userMain.getBatchLevel(), String.valueOf(currYear), String.valueOf(maxYear));
        //判断当前用户是否已经关注该专业
        boolean isFav = userFavoriteService.isFav("major", userId, "", "", "", majorCode);
        request.setAttribute("majorInfo", majorInfo);
        request.setAttribute("lqMajorList", lqMajorList);
        request.setAttribute("isFav", isFav);
        request.setAttribute("maxYear", maxYear);
        request.setAttribute("userMain", userMain);
        return "app/major";
    }
}
